'use strict';
const crypto = require('crypto');

const Service = require('egg').Service;
const { Op } = require("sequelize");

class UserService extends Service {
    async register(params) {
        const { model } = this.app

        const password = crypto.createHash('md5').update(params.password).digest('hex')
        const sql = {
            where: {
                [Op.or]: [
                    { email: params.email },
                    { name: params.name }
                ]
            },
            defaults: {
                name: params.name,
                email: params.email,
                password: password,
                score_level: params.scoreLevel,
                create_time: (new Date).getTime() / 1000,
                update_time: (new Date).getTime() / 1000
            }
        }
        const result = await model.User.findOrCreate(sql)
        return result
    }
    async signIn(params) {
        const { model } = this.app

        const sql = {
            where: { email: params.email, password: crypto.createHash('md5').update(params.password).digest('hex') }
        }
        const result = await model.User.findOne(sql)
        return result
    }
}

module.exports = UserService;
